function mountElement(element,props){
    var e=React.createElement(eval(element), props);
    e=React.createElement(Wrap,{customerId:customerId},e);
    React.unmountComponentAtNode($('#list').get(0));
    React.render(e,$('#list').get(0));
}
var NavBar = React.createClass({
    handleShowLoginModal:function(){
        $('#loginModal',"#wrapper").modal('show');
    },
    render: function() {
        var rightButtons=[];
        var flag=$.cookie("flag")||"";
        if(flag.indexOf("p")>=0){
                rightButtons.push(<li><a href={"/manage/main.html"} >管理</a></li>);
        }
        if(this.props.customerId){
            return(<div id="sidebar-wrapper" className="bg-info">
                    <div className="sidebar-brand">
                       <UserBadge customer={this.props.customer}/>
                    </div>
                   <ul className="sidebar-nav">
                        <li className="clearfix"><a onClick={function(){toPage('FilterableProductTable',{})}} href="javascript:;">附近的活动</a></li>
                        <li><a onClick={function(){toPage('ShopListPage',{})}} href="javascript:;">场馆搜索</a></li>
                        <li role="presentation" className="divider"></li>
                        <li><a onClick={function(){toPage('CustomerOrderListPage',{customerId:customerId})}.bind(this)} href="javascript:;">我的活动</a></li>
                        <li><a onClick={function(){toPage('UserJoinedPartners',{customerId:customerId})}.bind(this)} href="javascript:;">我的俱乐部</a></li>
                        <li role="presentation" className="divider"></li>
                        <li><a onClick={function(){toPage('CustomerSettingsPage',{customerId:customerId})}.bind(this)} href="javascript:;">设置</a></li>
                        {rightButtons}
                   </ul>
               </div>
               );
        }else{
            return(<div id="sidebar-wrapper"  className="bg-info">
                   <ul className="sidebar-nav">
                        <li className="sidebar-brand col-md-12">
                           <UserBadge customer={this.props.customer}/>
                           <button onClick={this.handleShowLoginModal.bind(this)} className="btn btn-warning">登录</button>
                        </li>
                        <li className="clearfix"><a onClick={function(){toPage('FilterableProductTable')}} href="javascript:;">附近活动</a></li>

                   </ul>
               </div>
               );
        }

    }
});

var CustomerSettingsPage = React.createClass({
   getInitialState: function() {
       return {balance:0};
   },
   componentDidMount: function() {
       var self=this;
       API.customerBalance({customerId:this.props.customerId},function(data){
           self.setState({balance:data.balance});
       });
   },
   openTopUp: function(amount){
       $('#userTopupModal',this.getDOMNode()).modal('show');
   },
   render: function() {
    var customer=this.props.customer||{};
    var createTime=new Date(customer.createTime).Format("yyyy-MM-dd")
     return (
       <div className="clear-both">
       <div className="panel panel-success">
         <div className="panel-heading">{customer.loginname}</div>
         <div className="panel-body">

            <div className="center-block col-md-8"><div><UserBadge customer={customer}/></div><div></div></div>
            <ul className="list-group">
                <li className="list-group-item">注册时间：{createTime} </li>
                <li className="list-group-item">余额：{this.state.balance} <button onClick={this.openTopUp.bind(this,100)} className="btn btn-success">充值</button></li>
                <li className="list-group-item"><a onClick={function(){toPage("PartnerApplyPage",{customerId:this.props.customerId})}.bind(this)} href="javascript:;">俱乐部加盟</a></li>
                
            </ul>
         </div>
       </div>
       <UserTopupModal amount="99" balance={this.state.balance} customerId={this.props.customerId} />
       </div>
     );
   }
 });

var UserTopupPage= React.createClass({
    getInitialState: function() {
        return {
            amount: this.props.amount||100
        };
    },
    handleAmountChange:function(e){
        if(e.target.value>=0){
            this.setState({amount:e.target.value})
        }
    },
    handleTopUp: function(){
        var that=this;
       $.post('/api/customers/'+this.props.customerId+'/balance',{amount:this.state.amount},function(data){
            wx.chooseWXPay({
                timestamp: data.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                nonceStr: data.nonceStr, // 支付签名随机串，不长于 32 位
                package: data.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
                signType: data.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                paySign: data.paySign, // 支付签名
                success: function (res) {
                    alert("充值成功");
                    toPage('CustomerSettingsPage',{customerId:that.props.customerId})
                }
            });

           //this.setState({balance:data.balance});
           //$(this.getDOMNode()).modal('hide');
       });
    },
    render:function(){
        var balance="";
        if(this.props.balance){
            balance=<div className="input-group block"><span className="col-xs-4">余额</span>{this.props.balance}</div>;
        }
        return (<div>
                
                  {balance}
                <div className="input-group block">
                  <span className="col-xs-4">充值金额</span>
                  <div className="block">
                    <a onClick={function(){this.setState({amount:200})}.bind(this)} href="javascript:;" className="btn btn-success">200</a>
                    <a onClick={function(){this.setState({amount:500})}.bind(this)} href="javascript:;" className="btn btn-success">500</a>
                    <a onClick={function(){this.setState({amount:1000})}.bind(this)} href="javascript:;" className="btn btn-success">1000</a>
                  </div>
                  <input onChange={this.handleAmountChange} className="form-control" name="amount" value={this.state.amount} data-rule-min="0" data-msg-min="妈呀，小学没毕业不认识负数！"/>
                </div>
                <div className="input-group block">
                  <button className="btn btn-success" onClick={this.handleTopUp}>去支付</button>
                </div>
                </div>);
    }
});

var UserTopupModal= React.createClass({
    componentDidMount: function() {
        if(this.props.show){
            $(this.getDOMNode()).modal('show');
        }
    },
    render:function(){
        var balance="";
        if(this.props.balance){
            balance=<span className="input-group-addon">余额{this.props.balance}</span>;
        }
        var amount=this.props.amount||100;
        return (<Modal id="userTopupModal">
            <UserTopupPage {...this.props} />
                </Modal>);
    }
});

var ShopLink = React.createClass({
    render:function(){
        var shop=this.props.shop||{}
        var location=shop.location||{}
        var distance=getGPSDistance(mylocation.lat,mylocation.lng,location.lat,location.lng)+'m'
        return <a  href={"http://m.amap.com/navi/?dest="+location.lng+","+location.lat+"&destName="+shop.name+"&hideRouteIcon=1&key="+amapKey}><span className="glyphicon glyphicon-map-marker" aria-hidden="true"/>{shop.name} <span className="badge">{distance}</span></a>
    }
})

var ShopList4Partner = React.createClass({
    getInitialState: function() {
        return {shops:[]};
    },
    componentDidMount: function() {
        API.shopsOfPartner({partnerId:this.props.partnerId},function(data){
            this.setState({shops:data.content});
        }.bind(this));
    },
    render:function(){
        var items=this.state.shops.map(function(shop){
            return (<li className="list-group-item"><ShopLink shop={shop} /></li>)
        })
        return (<div>
                 <ul className="list-group clear-both">
                    {items}
                 </ul>
             </div>
             ); 
    }
})

var JoinButton = React.createClass({
  getInitialState: function() {
    return {
      joined:true 
    };
  },
  componentDidMount: function() {
    $.get('/api/customers/'+this.props.customerId+'/partners/check',{partnerId:this.props.partnerId},function(){
      this.setState({joined:false})
    }.bind(this))
  },
  render: function() {
    if(this.state.joined){
      return (
        <div />
      );
    }else{
      return <button onClick={this.props.onClick} className="btn btn-success col-xs-12 col-md-4 pull-right">我要加入</button>
    }
    
  }
})

var PartnerDetailPage= React.createClass({
    getInitialState: function() {
        return {members:[]};
    },
    componentDidMount: function() {
        var self=this;
        API.partnerLinkedCustomers({partnerId:this.props.id},function(targets){
            self.setState({members:targets.content});
        });
    },
    handleJoinClub:function(){
        var customerId=this.props.customer.id;
        var partnerId=this.props.id;
        API.customerLinkPartner({customerId:customerId,partnerId:partnerId},function(data){
            //$(this.getDOMNode()).modal('hide');
            alert('您已经加入');
            //toPage('UserJoinedPartners',{customerId:customerId},'/my/clubs.html');
        }.bind(this));
    },
    render:function(){
        var nowTimeStamp=new Date().getTime();
        nowTimeStamp=nowTimeStamp-nowTimeStamp%(24*3600000)-8*3600000;
        var members=this.state.members.map(function(rel){
            var target=rel.target
            return (<div className="col-xs-3 col-md-2"><img className="avatar" src={target.picture?'/api/thumb/'+target.picture+'/64/64':'/img/avatar_default.jpg'} /><div>{target.name}</div></div>)
        })
        return (<div>
                <div className="btn-group  col-xs-12 alert">
                    <JoinButton customerId={this.props.customerId} partnerId={this.props.id} onClick={this.handleJoinClub} />
                </div>
                <div className="panel panel-info  clear-both">
                    <div className="panel-heading">场所</div>
                    <div className="panel-body"><ShopList4Partner partnerId={this.props.id}/></div>
                    <div className="panel-heading">近期活动</div>
                    <div className="panel-body">
                        <ProductList url={"/api/products?partner_id="+this.props.id+"&date="+nowTimeStamp+"&from=true"} />
                    </div>
                    <div className="panel-heading">过往活动</div>
                    <div className="panel-body">
                        <ProductList url={"/api/products?partner_id="+this.props.id+"&date="+nowTimeStamp} />
                    </div>
                    <div className="panel-heading">会员</div>
                    <div className="panel-body">
                        {members}
                    </div>
                    
                </div>
            </div>
            );
    }
});



var UserJoinedPartners = React.createClass({
     getInitialState: function() {
         return {members:[]};
     },
     componentDidMount: function() {
       this.props.customerId=this.props.customerId||customerId
       var self=this;
       API.customerLinkedPartners({customerId:this.props.customerId},function(targets){
           self.setState({members:targets.content});
       });
     },
     render:function(){
         var items=this.state.members.map(function(rel){
             var target=rel.target
             return (<li className="list-group-item"><a  onClick={function(){toPage('PartnerDetailPage',{customerId:customerId,id:target.id})}} href="javascript:;">{target.name} <span className="glyphicon glyphicon-menu-right pull-right" /></a></li>)
         })
         return (<div>
                 <ul className="list-group clear-both">
                    {items}
                 </ul>
             </div>
             );
     }
 });



var OrderRow = React.createClass({
    handleCancelOrder:function(){
        var self=this;
        if(confirm("是否要取消本次预定?")){
            API.customerCancelOrder({customerId:this.props.customerId,orderId:this.props.orderId},function(order){
                var state=self.state;
                state.status=order.statusText;
                self.setState(state);
            });
        }
    },
    handleOpenDetail:function(productId,url){
      toPage('ProductDetailPage',{customerId:customerId,id:productId});
      return false;
    },
    getInitialState: function() {
        return {product: {},status:""};
    },
    componentDidMount: function() {
        var order=this.props.order;
        var productId=order.productId;
        var self=this;
        API.getProduct({productId:productId},function(data){
            self.setState({product: data,status:order.orderStatus});
        })
    },
    render: function() {
        var order=this.props.order;
        var product = this.state.product||{};
        var location=product.location||{};
        var startTime=new Date(product.startTime).Format('MM-dd hh:mm')+' - '+new Date(product.endTime).Format('hh:mm');
        var dueTime=new Date(product.dueTime).Format('MM-dd hh:mm')
        var status = this.state.status;
        var picture=product.picture?'/api/thumb/'+product.picture+'/64/64':"/img/avatar_default.png";
        //
        if(product.dueTime&&product.dueTime>new Date()&&status=="已支付"){
            status= <button onClick={this.handleCancelOrder} className="btn btn-warning">取消报名</button>;
        }
        return (
        <div className="panel panel-success">
          <div className="panel-heading">{product.shopName}</div>
          <div className="panel-body">
                <table width="100%">
                    <tbody>
                        <tr>
                            <td width="60"><div><img width="60" src={picture}/></div></td>
                            <td colSpan="2">
                                <div><div><a onClick={this.handleOpenDetail.bind(this,product.id)} href="javascript:;" ><b>[{product.cat1}]{product.name}</b></a></div></div>
                            </td>
                            <td><div><a  href={"http://m.amap.com/navi/?dest="+location.lng+","+location.lat+"&destName="+product.shopName+"&hideRouteIcon=1&key="+amapKey}><span className="glyphicon glyphicon-map-marker" aria-hidden="true"/>{product.shopName}</a></div></td>
                        </tr>
                        <tr>
                            <td><div><span className="glyphicon glyphicon-user" aria-hidden="true"/>{product.quantity-product.stock}/{product.quantity}人</div></td>
                            <td colSpan="2"><div><span className="glyphicon glyphicon-time"/>{startTime}</div></td>
                            <td><div><span className="glyphicon glyphicon-yen"/><strong>{order.orderTotal} - {order.amount}人</strong></div></td>
                        </tr>
                        <tr>
                            <td colSpan="4">
                                <div>{status}<small>最迟取消时间：{dueTime}</small></div>
                            </td>
                        </tr>
                    </tbody>
                </table>
          </div>
        </div>

        );
    }
});

var CustomerOrderListPage = React.createClass({
    getInitialState: function() {
        return {orders: []};
    },
    componentDidMount: function() {
          this.props.customerId=this.props.customerId||customerId
          var customerId=this.props.customerId
          var self=this;
          API.customerOrdersWithProduct({customerId:customerId},function(data){
              self.setState({orders:data.content});
          });
    },
    render: function() {
        var rows=[];
        var self=this;
        this.state.orders.map(function(order){
            rows.push(<OrderRow customerId={self.props.customerId} orderId={order.orderId} order={order} />)
        });

        return (

            <div className="clear-both">
                <h3>我参加的活动</h3>
                <div>
                    {rows}
                </div>
            </div>
        );
    }
});


var JoinPartyModal = React.createClass({
    handleJoinParty: function(){
        var customerId=this.props.customerId;
        var amount=(this.props.female||0)+(this.props.male||0);
        var note=this.state.note;
        $.post('/api/customers/'+customerId+'/orders/single/step',{product_id:this.props.id,amount:amount,note:note},function(data){
            $('#partyModal').modal('hide');
            toPage('CustomerOrderListPage',{customerId:customerId});
        }.bind(this));
    },
    handleToTopup:function(amount){
        toPage('UserTopupPage',{customerId:this.props.customerId,amount:amount,balance:this.state.balance,show:true});
        //$('#userTopupModal').modal('show');
    },
    handleMaleChange:function(v){
        this.props.male=v;
        this.updateInfo();
    },
    handleFemaleChange:function(v){
        this.props.female=v;
        this.updateInfo();
    },
    updateInfo:function(){
        var amount=(this.props.female||0)+(this.props.male||0);
        $.get('/api/customers/'+this.props.customerId+'/promotions/check',{product_id:this.props.id,amount:amount},function(data){
            
            var cost=amount*this.props.product.price;
            for(var i in data){
                var rule=data[i]
                cost-=rule.amount;
            }
            this.setState({promotions:data,cost:cost})
        }.bind(this))
        this.state.cost=Math.max(amount*this.props.product.price,0);
        this.state.note='';
        this.setState(this.state);
    },
    getInitialState: function() {
        return {balance:0,cost:0,note:'',promotions:[]};
    },
    componentDidMount: function() {
        API.customerBalance({customerId:this.props.customerId},function(data){
               this.state.balance=data.balance;
               this.setState(this.state);
           }.bind(this));
    },
    render:function(){
        var btn="";
        var joinSate="btn btn-success";
        if(this.state.balance<this.state.cost){
            btn=<div> 您需要支付 <strong>{this.state.cost}¥</strong> <small>(以实际优惠后的价格为准)</small> 余额:{this.state.balance}  <button onClick={this.handleToTopup.bind(this,this.state.cost-this.state.balance)} className="btn btn-warning">余额不足去充值</button></div>
            joinSate="btn btn-success disabled";
        }else{
            btn=<div> 您需要支付 <strong>{this.state.cost}¥</strong> <small>(以实际优惠后的价格为准)</small> 余额:{this.state.balance}</div>
        }
        var promotions=this.state.promotions.map(function(rule){
            return (<div>{rule.name} <small>{rule.amount}¥</small></div>)
        })
        return (<Modal id="partyModal">
                     <NumberSelector name="numMale" onChange={this.handleMaleChange.bind(this)} label="参加人数" />
                     <div className="alert alert-info" role="alert">优惠（一次报名中除了报名者本人，其他用户不重复享受会员优惠）：{promotions}</div>
                     <div className="input-group-btn">
                          {btn}
                      </div>

                     <div className="input-group">
                          <span className="input-group-addon">备注:</span>
                          <input id="note" className="form-control" name="note" rows="3" defaultValue={this.state.note} placeholder="备注"></input>
                      </div>
                     <div className="input-group">
                     <span className="input-group-btn">
                         <button className={joinSate} onClick={this.handleJoinParty.bind(this,1)}>报名</button>
                       </span>
                     </div>
                </Modal>)
    }
});


var PartnerApplyPage = React.createClass({

    componentDidMount: function() {
        var thisElement=this.getDOMNode();
        $('.fileinput',thisElement).fileinput({uploadAsync:false,previewFileType: "image",multiple:false,language: "zh",uploadUrl: "/api/attachments"}).on('filebatchuploadsuccess', function(event, data) {
            var form = data.form, files = data.files, extra = data.extra, 
                response = data.response, reader = data.reader;
            $('#picture_id',thisElement).val(response.filename)

        }.bind(this));
        $('form',thisElement).validate();
    },
    handlePartnerApply: function(){
        var thisElement=this.getDOMNode();
        if($('form',thisElement).valid()){
            $.post("/api/customers/"+this.props.customerId+"/partners/apply",$('form.PartnerApplyForm',thisElement).serialize(),function(){
                alert('您的申请已提交，申请通过后我们将电话联系您！');
                history.back();
            }.bind(this));
        }
    },
    render:function(){
        return (
            <div className="panel">
             <div className="panel-body">
                <form className="PartnerApplyForm">
                  <input type="hidden" id="picture_id" name="picture_id" />
                  <div className="form-group">
                    
                    <input type="text" className="form-control" name="name" id="name" placeholder="名称" data-rule-required="true"  data-msg-required="此项不能为空！"/>
                    <label for="name" className="alert alert-default">请输入俱乐部名称</label>
                  </div>
                  <LocationPicker />
                  <div className="form-group">
                    
                    <input type="phone" className="form-control" name="contact_phone" id="phone" placeholder="电话号码" data-rule-required="true"  data-msg-required="此项不能为空！"/>
                    <label for="phone" className="alert alert-default">请输入固定号码或手机号</label>
                  </div>

                  <div>
                      <input name="file" type="file" accept="image/*" className=" fileinput form-control"/>
                    </div>
                  
                  <button type="button" onClick={this.handlePartnerApply.bind(this)} className="btn btn-primary col-xs-12 col-md-2">提交申请</button>
                  <hr/>
                </form>
             </div>
            </div>
            )
    }
})




var ShopListPage = React.createClass({
    handleCityChanged:function(e){
        var city=$(e.target).val()
        $.get('/api/shops?page=0&city='+city,function(data){
            this.setState({shops:data.content})
        }.bind(this))
    },
    getInitialState: function() {
        return {
            shops: []
        };
    },
    render: function() {
        
        return (
            <div>
                <CitySelector inline="true" onChange={this.handleCityChanged} />
                <ShopList shops={this.state.shops}/>
            </div>
        );
    }

});

var ShopRow = React.createClass({

    render: function() {
        var shop=this.props.shop||{};
        var address=shop.address||{};
        var partner=shop.partner||{};
        var location=shop.location||{};
        var picture=partner.avatar?'/api/thumb/'+partner.avatar+'/256/256':'/img/avatar_default.jpg'
        return (
            <div className="panel panel-success">
                <div className="panel-body">
                <a href="javascript:;" >
                    <table>
                    <tr onClick={toPage.bind(this,'PartnerDetailPage',{customerId:customerId,id:partner.id},null)}><td rowSpan="2" className="col-xs-4 col-md-2"><img width="64" src={picture}/></td><td colSpan="2"><h3>{partner.name}</h3></td></tr>
                    <tr><td className="col-xs-4">{shop.name}</td><td><a className="b" href={"http://m.amap.com/navi/?dest="+location.lng+","+location.lat+"&destName="+address.street+"&hideRouteIcon=1&key="+amapKey}><span className="glyphicon glyphicon-map-marker" />{address.street}</a></td></tr>
                    </table>
                </a>
                </div>
            </div>
        );
    }
});


var ShopList = React.createClass({

    render: function() {
        var rows=this.props.shops.map(function(shop){
            return <ShopRow shop={shop} />
        })
        return (
            <div>{rows}</div>
        );
    }

});


